package com.sinosoft.web.common;

import com.sinosoft.hydra.um.LoginUser;
import com.sinosoft.hydra.um.helper.AuthContextHelper;
import org.springframework.core.MethodParameter;
import org.springframework.web.bind.support.WebDataBinderFactory;
import org.springframework.web.context.request.NativeWebRequest;
import org.springframework.web.method.support.HandlerMethodArgumentResolver;
import org.springframework.web.method.support.ModelAndViewContainer;
import org.springframework.web.multipart.MultipartHttpServletRequest;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * Created with IntelliJ IDEA.
 * User: New
 * Date: 13-6-14
 * Time: 上午10:33
 * To change this template use File | Settings | File Templates.
 */
public class MyHandlerMethodArgumentResolver implements HandlerMethodArgumentResolver {

    public boolean supportsParameter(MethodParameter parameter) {
        Class claz = parameter.getParameterType();
        return (WebInput.class.equals(claz) || FileWebInput.class.equals(claz) || LoginUser.class.equals(claz));
    }

    public Object resolveArgument(MethodParameter parameter, ModelAndViewContainer mavContainer, NativeWebRequest webRequest, WebDataBinderFactory binderFactory) throws Exception {
        Class claz = parameter.getParameterType();
        HttpServletRequest request = (HttpServletRequest) webRequest.getNativeRequest();
        if (WebInput.class.equals(claz)) {
            return WebInput.getInstance(request);
        } else if (FileWebInput.class.equals(claz)) {
            return new FileWebInput((MultipartHttpServletRequest) request);
        } else {
            return getLoginUser();
        }
    }

    private static LoginUser getLoginUser() {
        return AuthContextHelper.getLoginUser();
    }
}
